package com.person.jc.web.template;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.activerecord.tx.TxConfig;
import com.person.jc.common.Constants;
import com.person.jc.common.FileUtil;
import com.person.jc.config.GlobalConfig;
import com.person.jc.entity.TsUser;
import com.person.jc.service.base.device.BdDeviceRelationService;
import com.person.jc.service.service.BsOrderService;
import com.person.jc.service.template.TemplateService;
import com.person.jc.service.test.certificate.MakeService;
import com.person.jc.service.test.inspect.BsRepairRegLogService;
import com.person.jc.utils.SessionKit;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

public class TemplateManageController extends Controller {
	
	public void init(){
		setAttr("menuId", getPara("menuId"));
		
		String template = getPara("template");
		/*
		 * 1. 原始记录单
		 * 2. 检定证书
		 * 3. 检定结果通知书
		 * 4. 证书清单
		 * 5. 维修确认单
		 */
		String[] path = {"originalRecord","certificate","notice","list","confirmations"};
		render(path[Integer.parseInt(template)]+"/main.jsp");
	}


	public void showTemplate(){ //TODO显示原始单据
		String equId=getPara("id");
		String orderId=getPara("orderId");
		String deviceType=getPara("deviceType");
		String gasType=getPara("gasTypeId");
		gasType=gasType.toLowerCase();
		String sort=getPara("sort");

		Record equ=TemplateService.me.findTempInfoByEquId(equId);

		String verify="";

		//查询鉴定依据
		if(deviceType.equals("2") || deviceType.equals("1")){
		 	Record verifyRecord=	Db.findFirst("select verify_no from bd_verify_basis where device_type="+deviceType+" and `status`=1 and if_valid=1 and valid_date >= now() ORDER BY create_date desc");
		 	verify=verifyRecord.getStr("verify_no");
		}else{
			Record verifyRecord= Db.findFirst("SELECT * FROM bd_verify_basis vb INNER JOIN bd_device_info di ON vb.device_id_ = di.device_id WHERE vb.device_type = 3 AND vb.`status` = 1 AND vb.if_valid = 1 AND vb.valid_date >= now() AND di.device_name = '"+gasType.toUpperCase()+"' ORDER BY create_date DESC");
			verify=verifyRecord.getStr("verify_no");
		}

		SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd");
		String date = format0.format(new Date());//这个就是把时间戳经过处理得到期望格式的时间

		//查询检定员与核验员
		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		String verifiedUser=tsUser.getUserName();
		String verifiedUserId=tsUser.getUserId();
		String checkedUser="";
		String checkedUserId="";
		List<Record> recordUsers=Db.find("SELECT u.user_id, u.user_name FROM bs_task_assign_user au INNER JOIN ts_user u ON au.user_id = u.user_id WHERE au.device_type = "+deviceType+" AND au.order_id = '"+orderId+"' order by assign_id desc");
		if(recordUsers!=null && recordUsers.size()>0){
			for(Record record:recordUsers){
				if(!record.getStr("user_id").equals(tsUser.getUserId())){
					checkedUser=record.getStr("user_name");
					checkedUserId=record.getStr("user_id");
					break;
				}
			}
		}

		//获取维修记录
		Record recordRL= Db.findFirst("select * from bs_recondition_log where order_id=? and equ_id=?",orderId,equId);

		setAttr("address",recordRL.getStr("address"));

		setAttr("gasType",gasType);
		setAttr("equ", equ);
		setAttr("orderId",orderId);
		setAttr("equId",equId);
		setAttr("sort",sort);
		setAttr("verify",verify);
		setAttr("date",date);
		setAttr("verifiedUser",verifiedUser);
		setAttr("verifiedUserId",verifiedUserId);
		setAttr("checkedUser",checkedUser);
		setAttr("checkedUserId",checkedUserId);

		Map<String,String> map=createOriginalRecordName();
		setAttr("zi",map.get("zi"));
		setAttr("hao",map.get("hao"));

		String filename="";
		if(deviceType.equals("3")){
			filename=gasType;
		}else if(deviceType.equals("1")){
			filename="qiping";  //暂时没有气瓶的准确相关信息
		}else if(deviceType.equals("2")){
			filename="konghu";
		}
		render("originalRecord/"+filename+".jsp");
	}

	/**
	 * 保存模板时，多个原始单据的路径用，隔开。
	 */
	@Before(Tx.class)
	public void saveTemplate(){
		String templateData=getPara("tempData");
		String orderId=getPara("orderId");
		String scopeId=getPara("scopeId");
		String equId=getPara("equId");
		String sort=getPara("sort"); //用来记录当前提交上来的原始记录单的路径排序位置
		String keyObj=getPara("keyObj");
		String isPass=getPara("isPass");
		String type=getPara("type");
		String checkUser=getPara("checkUser");
		String verifiedUser=getPara("verifiedUser");
		String verify=getPara("verify");


		String fileName=orderId+"_"+equId;
		String originalRecordStr="";
		String scopesStr="";
		String isOk="0";
		if(!sort.equals("-1")){
			fileName+="_"+sort+".html";
			Record record=TemplateService.me.findBSReconditionLog(orderId,equId);
			String[] originalRecords=record.getStr("original_record").split(",");
			String[] scopesArray=record.getStr("scopes").split(",");

			originalRecords[Integer.valueOf(sort)]=fileName;
			scopesArray[Integer.valueOf(sort)]=scopeId;

			originalRecordStr=StringUtils.join(originalRecords,",");
			scopesStr=StringUtils.join(scopesArray,",");



			int pathCount=0;
			for (String path: originalRecords) {
				if(StringUtils.isNotBlank(path)){
					pathCount++;
				}
			}
			if(pathCount==originalRecords.length){
				isOk="1"; //表示所有的原始记录单都有自己的保存路径了
			}


		}else{
			fileName+=".html";
			originalRecordStr=fileName;
			scopesStr=scopeId;
			isOk="1";
		}

//		String uuid= UUID.randomUUID().toString();


		TemplateService.me.updateBSReconditionLog(orderId,equId,originalRecordStr,isOk,scopesStr);

		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		TemplateService.me.saveOriginalRecordKeyValue(orderId,equId,type,isPass,keyObj,tsUser.getUserId(),checkUser,verifiedUser,verify);




		//原始记录单已经填写完毕，把订单推向证书制作
		if(isOk.equals("1")){

			//查询order类型
			Record orderRec=Db.findFirst("select bo.order_type from bs_order bo where bo.order_id='"+orderId+"'");
			String sql1="";
			if(orderRec.getInt("order_type")==1){
				sql1="SELECT count(boe.order_id) onum, sum(brl.original_record_ok) rnum, sum(boe.if_cert) cnum  FROM bs_order_equipment boe LEFT JOIN bs_recondition_log brl ON brl.equ_id = boe.equ_id WHERE boe.order_id = '"+orderId+"'";
			}else if(orderRec.getInt("order_type")==2){
				sql1="SELECT count(boe.order_id) onum, sum(brl.original_record_ok) rnum, sum(boe.if_cert) cnum FROM bs_order_equipment boe LEFT JOIN bs_repair_reg_log brrl ON boe.equ_id = brrl.equ_id INNER JOIN bs_repair_confirm_log brcl ON brcl.log_id = brrl.log_id AND brcl.confirm_status = 1 LEFT JOIN bs_recondition_log brl ON brl.equ_id = boe.equ_id WHERE boe.order_id = '"+orderId+"'";
			}

			//一个订单可以接收多种类型设备，所以一种类型设备的OK不能说明是ok的。应该改订单下的不同种类的设备都ok了。
			Record re=Db.findFirst(sql1);
			if((re.get("onum")+".0").equals(re.get("rnum").toString())){

				if(Integer.valueOf(re.get("cnum").toString())>0){

					BsOrderService.me.updateFlow(orderId, Constants.FLOW_WX_WXRW);
				}else{
					BsOrderService.me.updateFlow(orderId, Constants.FLOW_JCWX_SQKP);
				}
			}
		}

		FileUtil.createFile(GlobalConfig.getTemplateDataRealPath(),fileName,templateData);
		renderText("success");
	}



	public void findBzwzByScopeId(){
		String scopeId=getPara("scopeId");
		renderJson(TemplateService.me.findBzwzByScopeId(scopeId));
	}

	public void viewOriginalRecord(){
		String fileName=getPara("fileName");
		String content=FileUtil.readFileContent(GlobalConfig.getTemplateDataRealPath(),fileName,"html");
		setAttr("content", content);
		render("originalRecord/view.jsp");

	}

	public void loadCertResult(){
		render("certificate/certResult.jsp");
	}

	/**
	 * 保存证书
	 */
	public void saveCert(){
		String content=getPara("content");
		String orderId=getPara("orderId");
		String equId=getPara("equId");
		String isPassed=getPara("isPassed");

		String fileName="cert_"+orderId+"_"+equId+".html";

		FileUtil.createFile(GlobalConfig.getTemplateDataRealPath(),fileName,content);


		Map<String,Object> map=new HashMap<String,Object>();
		TsUser tsUser = (TsUser) SessionKit.get().getAttribute(Constants.LOGIN_USER);
		map.put("optUser", tsUser.getUserId());
		map.put("orderId",orderId);
		map.put("equId",equId);
		map.put("isPassed",isPassed);
		map.put("savePath",fileName);
		TemplateService.me.saveBsCert(map);

		renderText("success");

	}

	/**
	 * 查看证书正面
	 */
	public void showCertFront(){
		String orderId=getPara("orderId");
		String equId=getPara("equId");

		Record record=TemplateService.me.findCertFrontInfoByOrderId(orderId,Integer.valueOf(equId));


		//查询证书相关信息，依据、检查、核验人员
		List<Record> certInfos=Db.find("select verify,verified_user,check_user,is_pass from bs_certificate_key_value where order_id=? and equ_id=?",orderId,equId);
		String verifies="";
		String verifiedUser="";
		String checkUser="";
		String isCert="1"; //0为通知书，1为证书


		for (Record re:certInfos){
			verifies+="  ;  "+re.getStr("verify");
			verifiedUser=re.getStr("verified_user");
			checkUser=re.getStr("check_user");
			if(isCert.equals("1") && re.getStr("is_pass").equals("false")){
				isCert="0";
			}

		}
		verifies=verifies.substring(3);

     	//查询鉴定日期
		Record dateRec=Db.findFirst("select rec_id, validity_date, opt_date from bs_recondition_log where order_id=? and equ_id=?",orderId,equId);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date=format.format(dateRec.getDate("opt_date"));
		String[] dates=date.split("-");

		setAttr("verifYear",dates[0]);
		setAttr("verifMonth",dates[1]);
		setAttr("verifDay",dates[2]);

		setAttr("info",record);

		setAttr("verifies",verifies);
		setAttr("checkUser",checkUser);
		setAttr("checkUserQM",Db.findFirst("select img_url from bd_sign where user_id=?",checkUser).getStr("img_url"));
		setAttr("verifiedUser",verifiedUser);
		setAttr("verifiedUserQM",Db.findFirst("select img_url from bd_sign where user_id=?",verifiedUser).getStr("img_url"));

		setAttr("certId",dateRec.getInt("rec_id"));
		String validityYear="";
		String validityMonth="";
		String validityDay="";
		if(dateRec.getDate("validity_date")!=null){
			String date2=format.format(dateRec.getDate("validity_date"));
			String[] dates2=date2.split("-");
			validityYear=dates2[0];
			validityMonth=dates2[1];
			validityDay=dates2[2];
		}
		setAttr("validityYear",validityYear);
		setAttr("validityMonth",validityMonth);
		setAttr("validityDay",validityDay);


		if(isCert!=null && isCert.equals("1")){
			setAttr("result","合格");
			render("certificate/certFront.jsp");
		}else{
			setAttr("result","不合格");
			render("certificate/noticeFront.jsp");

		}
	}

	/**
	 * 查看证书背面
	 */
	public void showCertBack(){
		String orderId=getPara("orderId");
		String equId=getPara("equId");
		String fileName="cert_"+orderId+"_"+equId;
		String content=FileUtil.readFileContent(GlobalConfig.getTemplateDataRealPath(),fileName,"html");
		setAttr("content", content);
		render("certificate/back.jsp");
	}


	private Map<String,String> createOriginalRecordName(){
		Map<String,String> 	map =new HashMap<String,String>();
		map.put("zi","京");
		map.put("hao","JD"+String.valueOf(new Date().getTime()));
		return map;
	}

	public static void main(String[] args) {
		TemplateManageController templateManageController=new TemplateManageController();
		Map<String,String> map=templateManageController.createOriginalRecordName();
		System.out.print(map.get("zi")+"字第"+map.get("hao")+"号");
	}
	
}
